<template>
    <div>
        <Form ref="form1"  :model="formItem"  :label-width="120">
            <Row  v-show="!switchFlag" class="query-form" style="padding-top: 15px">
                <Col span="8">
                    <FormItem label="岗位名称：">
                        <Input  class="query-form-el" v-model="formItem.positionName"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="公司" prop="orgId">
                        <cascader-dom ref="company1" :orgTree="true"  :currentOrgId="formItem.companyId" :currentOrgName="formItem.companyName"  @setOrgInfo="formItemCompanyNamesetOrgInfo" :rootAffordIf="true"></cascader-dom>
                    </FormItem>
                </Col>
                <Col span="8">
                    <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text"  >展开∨</Button>
                    <Button @click="reset" class="ivu-btn-reset"  >重置</Button>
                    <Button   class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
                </Col>
            </Row>
            <Row  v-show="switchFlag" class="query-form" style="padding-top: 15px">
                <Col span="8">
                    <FormItem label="岗位名称：">
                        <Input  class="query-form-el" v-model="formItem.positionName"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="公司" prop="orgId">
                        <cascader-dom ref="company2" :orgTree="true"  :currentOrgId="formItem.companyId" :currentOrgName="formItem.companyName"  @setOrgInfo="formItemCompanyNamesetOrgInfo" :rootAffordIf="true"></cascader-dom>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="部门" prop="orgId">
                        <cascader-dom ref="child2" :orgTree="true" :department="true" :currentOrgId="formItem.orgId" :currentOrgName="formItem.orgName"  @setOrgInfo="formItemOrgNamesetOrgInfo" :rootAffordIf="true"></cascader-dom>
                    </FormItem>
                </Col>
            </Row>
            <Row  v-show="switchFlag" class="query-form" style="padding-top: 15px">
                <Col span="24">
                   <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text"  >收起∧</Button>
                   <Button @click="reset" class="ivu-btn-reset"  >重置</Button>
                   <Button   class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
               </Col>
           </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" type="success"  class="ivu-btn-add" icon="md-add" @click="modaltage">新增</Button>
                </Col>
            </Row>
        </Form>
    
        <Table ref='table' :height="tableHeight" size="small" :loading="buttonLoading" class="table" no-data-text="没有查询到相关数据!"
               highlight-row stripe border :columns="columns3" width="100%" :data="data1">
        </Table>
        <Page :total="pagedata.total"   :fromPage="pagedata.fromPage" :pageSize="pagedata.pageSize"
              @on-change="pageChange" @on-page-size-change='sizeChange' show-total show-sizer show-elevator/>
        
        <Modal v-model="qrVisible" >
            <div id="qrcode" ref="qrcode" ></div>
        </Modal>
        <Modal v-model="modal2"  :transfer=false :width=600 :closable="false" :mask-closable="false" :title="tage?'修改':'添加'">
            <Form ref="formCustom" :model="formCustom" :rules="ruleCustom"  label-position="top">
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="11">
                        <FormItem label="岗位名称" prop="userName">
                            <Input type="text" v-model="formCustom.positionName"></Input>
                            <Input type="text" v-show="false" v-model="formCustom.positionName"></Input>
                        </FormItem>
                    </Col>
                    <Col span="11">
                        <FormItem label="组织机构" prop="orgId">
                            <cascader-dom ref="child" :orgTree="true"  :department="true"  :currentOrgId="formCustom.orgId" :currentOrgName="formCustom.orgName"  @setOrgInfo="orgNamesetOrgInfo" :rootAffordIf="true"></cascader-dom>
                        </FormItem>
                    </Col>
                </Row>
               <!-- <Row type="flex" justify="center" class="code-row-bg">
                    <Col span="23" >
                        <FormItem>
                            <Button    class='ivu-btn-save' @click="modalok" >确定</Button>
                            <Button type="text"  class='ivu-btn-cancel'  @click="modalcancel" >取消</Button>
                        </FormItem>
                    </Col>
                </Row>-->
            </Form>
            <div slot="footer">
                <Button    class='ivu-btn-save' @click="modalok" >确定</Button>
                <Button type="text"  class='ivu-btn-cancel'  @click="modalcancel" >取消</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import cascaderDom from "../../../components/cascader-dom.vue"
    import { sessionStorage } from '../../../common/cacheUtils.js';
    import {Api} from '../../../api/index.js'
    import QRCode from "qrcodejs2";

    export default {
        components: {
            cascaderDom,QRCode 
        },
        data() {
            return {
                orgId:'',
                orgName:'',
                switchFlag: false,
                tableHeight:450,
                buttonLoading:false,
                formItem: {
                    userName: "",
                    companyId: "",
                    companyName:"",
                    orgId: "",
                    orgName:"",
                },

                formCustom: {
                    userName:'',
                    loginId:'',
                    orgId : '',
                    companyId: '',
                    password:'',
                    positionId:'1'
                },
                pagedata: {
                    total: 0, //总条数
                    fromPage: 1,//从n条开始
                    pageSize: 10//每页多少条
                },
                tage: false,
                qrVisible:false,
                modal2: false,
                ruleCustom: {
                    positionName: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur'
                    }],
					orgName: [{
						required: true,
						message: '  ',
						trigger: 'blur'
					}],
                },
                columns3: [{
                    type: 'index',
                    title: '序号',
                    width: 80,
                    align: 'center'
                },
                    {
                        title: '岗位名称',
                        /*width: 200,*/
                        key: 'positionName'
                    },
                    {
                        title: '公司',
                        /*width: 200,*/
                        key: 'companyName'
                    },
                    {
                        title: '部门',
                        /*width: 200,*/
                        key: 'orgName'
                    },
                    {
                        title: '操作',
                        fixed: 'right',
                        align: 'center',
                        width:230,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                       click: () => {
                                           this.$nextTick (function () {
                                                this.showQrcode(params.row);
                                            })
                                        }
                                    }
                                }, '生成二维码'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                       click: () => {
                                            this.modify(params)
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: ( sessionStorage('userId').getObject('userId').loginId != this.Common.admin) ? '#d0d0d0' :'red',
                                        pointerEvents: (sessionStorage('userId').getObject('userId').loginId != this.Common.admin) ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.remove(params)
                                        }
                                    }
                                }, '删除')
                        ]);
                    }
                }
                ],
                data1: []
            }
        },
        watch:{
            "modal2":function(qw,er){
                if(qw && this.tage){
                    setTimeout(()=>{
                        this.$refs.child.setCurrentOrg();
                    },100)
                }else{
                    this.$refs.child.resetCurrentOrg();
                }
            }
        },
        mounted: function() {
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            //页面加载执行的查询函数,返回的总条数,激活前端分页插件的页码功能.
            let companyId = sessionStorage('userId').getObject('userId').companyId;
            let companyName = sessionStorage('userId').getObject('userId').companyName;
            this.formItem.companyId = companyId;
            this.formItem.companyName = companyName;
             setTimeout(()=>{
                    this.$refs.company1.setCurrentOrg();
                    this.$refs.company2.setCurrentOrg();
                },100)
            this.query();
        },
        methods: {
            switchQuery(flag){
                this.switchFlag = flag;
                if(!this.switchFlag){
                    this.tableHeight = this.tableHeight+44;
                }else{
                    this.tableHeight = this.tableHeight - 44;
                }
            },
            formItemOrgNamesetOrgInfo(data){
                this.formItem.orgId = data[data.length - 1];
            },
            formItemCompanyNamesetOrgInfo(data){
                this.formItem.companyId = data[data.length - 1];
            },
            orgNamesetOrgInfo(data){
                this.formCustom.orgId = data[data.length - 1];
            },
            sizeChange(size){
                this.pagedata.pageSize = size
                this.query()
            },
            pageChange(pagenum){
                this.pagedata.fromPage = pagenum
                this.query()
            },
            /**
            * [addText 向canvas添加文字]
            * @param {[type]} canvassize [canvas宽高]
            * @param {[type]} fontsize   [文字大小]
            * @param {[type]} padding    [周围留空隙]
            */
            addText(name,canvassize,fontsize,padding,divBackground="#fff",fontColor="#a50054"){
                var canvases = this.$refs.qrcode.getElementsByTagName('canvas');
                var fontsizeH = fontsize+padding*3;         //文字高度
                var rectW = 0;                              //长方形背景宽度
                var width = 0;
                var centerx = canvassize/2 - rectW/2;       //居中的x
                var centery = canvassize/2 - fontsizeH/2;   //居中的y
                var ctx = canvases[0].getContext("2d");
                width = ctx.measureText(name).width; //文字长度,不知道为什么这里的width是中文字数的10倍，故需要乘上fontsize/10获取到真实的文字宽度
                rectW = width*fontsize/10+padding*2;      //长方形背景宽度，应左右留padding
                centerx = canvassize/2 - rectW/2;         //长方形背景居中的x
                centery = canvassize/2 - fontsizeH/2      //长方形背景居中的y
                ctx.fillStyle=divBackground;              //长方形背景颜色
                ctx.fillRect (centerx,centery,rectW, fontsizeH);
                ctx.font = fontsize+"px Calibri";         //设置文字大小
                ctx.fillStyle = fontColor;
                ctx.fillText(name, centerx+padding, centery+fontsize+padding/2)
                //经测试，若参数y只填centery，则文字显示在长方形背景的上边，所以需要加上fontsize长方形背景才能包裹文字
            },
            showQrcode(row) {
                var data = {
                    orgInfo:{
                        orgId:row.orgInfo.orgId,
                        orgName:row.orgInfo.orgName,
                        parentId:row.orgInfo.parentId,
                        parentName:row.orgInfo.parentOrgName
                    },
                    position:{
                        positionId:row.positionId,
                        positionName:row.positionName
                    },
                    companyId:row.orgInfo.companyId,
                    companyName:row.orgInfo.companyName
                }
                document.getElementById("qrcode").innerHTML = "";
                var qrcode = new QRCode('qrcode', { // 第一个入参是组件id
                    text: JSON.stringify(data), // 生成二维码的文本
                    width: 800,
                    height: 800,
                    colorDark: '#000000', // 二维码色
                    colorLight: '#ffffff', // 背景色
                    correctLevel: QRCode.CorrectLevel.H // 容错等级，H是heigh，最高，所以二维码看起来很密
                })
                this.downloadE(row.positionName);
            },
            // 点击下载app二维码
            downloadE(name) {
                this.addText(name,800,60,5);
                var canvasData = this.$refs.qrcode.getElementsByTagName('canvas')
                var a = document.createElement("a");
                var event = new MouseEvent("click"); // 创建一个单击事件
                a.href = canvasData[0].toDataURL("image/png");;
                a.download = name;
                a.dispatchEvent(event); // 触发a的单击事件
            },
            query() {
                this.buttonLoading=true
                let data = {};
                data.fromPage = this.pagedata.fromPage;
                data.pageSize = this.pagedata.pageSize;

                data = Object.assign(data,JSON.parse(JSON.stringify(this.formItem)));
                this.$http.get(Api.queryPosition, {
                    params: data
                }).then(res => {
                    res.data.data.map(i => {
                        if(i.orgInfo != null){
                            i.orgName = i.orgInfo.orgName;
                            i.orgId = i.orgInfo.orgId;
                            i.companyName = i.orgInfo.companyName;
                        }
                    })
                    this.pagedata.total = res.data.total;
                    this.data1 = res.data.data;
                    this.buttonLoading=false
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            reset() {
                this.formItem = {
                    positionName: "",
                    orgId:"",
                    orgName:"",
                    companyId:"",
                    companyName:""
                };
                setTimeout(()=>{
                    this.$refs.child2.setCurrentOrg();
                    this.$refs.company1.setCurrentOrg();
                    this.$refs.company2.setCurrentOrg();
                },100)
                this.query();
            },
            modaltage() {
                this.modal2 = true;
                this.formCustom = {

                }
            },
            modify(params) {
                this.tage = true;
                this.modal2 = true;
                this.formCustom = {
                    orgId: params.row.orgId,
                    orgName: params.row.orgName,
                    positionName: params.row.positionName,
                    positionId:params.row.positionId
                }
            },
            remove(params) {
                this.$http.get(Api.deletePosition + '/'+ params.row.positionId).then(res => {
                    this.$Message.success('删除成功!');
                    this.query();
                }).catch(e => {
                    this.$Message.error('请求失败');
                })
            },
            modalok() {
                this.$refs["formCustom"].validate((valid) => {
                    if(valid) {
                        if(this.tage) {
                            // this.formCustom.orgId = this.formCustom.orgId[this.formCustom.orgId.length - 1];
                            this.formCustom.orgInfo = {"orgId" : this.formCustom.orgId};
                            delete this.formCustom['orgId'];
                            delete this.formCustom['orgName'];
                            this.$http.post(Api.updatePosition, this.formCustom).then(res => {
                                this.tage = false
                                this.modal2 = false
                                this.$Message.success('成功!');
                                this.query();
                            }).catch(e => {
                                this.$Message.error('请求失败');
                            })
                        } else {
                            //this.formCustom.orgId = this.formCustom.orgId[this.formCustom.orgId.length - 1];
                            this.formCustom.orgInfo = {"orgId" : this.formCustom.orgId};
                            delete this.formCustom['orgId'];
                            this.$http.post(Api.addPosition, this.formCustom).then(res => {
                                this.modal2 = false
                                this.$Message.success('成功!');
                                this.query();
                            }).catch(e => {
                                this.$Message.error('请求失败');
                            })
                        }
                    } else {
                        this.$Message.error('不能为空!');
                    }
                })
            },
            modalcancel() {
                this.tage = false
                this.modal2 = false
            },
        }

    }
</script>
